package com.yupi.yuaiagent.tools;

import org.springframework.ai.tool.annotation.Tool;
import org.springframework.ai.tool.annotation.ToolParam;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * 终端操作工具类
 */
public class TerminalOperationTool {

    @Tool(description = "Execute a command in the terminal")
    public String executeCommand(@ToolParam(description = "Command to execute in the terminal") String command) {
        StringBuilder outStringBuilder = new StringBuilder();
        try {

            Process process;
            boolean isWindows = System.getProperty("os.name").toLowerCase().contains("win");
            if (isWindows) {
                process = Runtime.getRuntime().exec("cmd /c " + command);
            } else {
                process = Runtime.getRuntime().exec(command);
            }

            String charset = isWindows ? "GBK" : "UTF-8";
            try(BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream(),charset))) {
                String line;
                while ((line = bufferedReader.readLine()) != null) {
                    outStringBuilder.append(line).append("\n");
                }
            }
            int exitCode = process.waitFor();
            if (exitCode != 0) {
                outStringBuilder.append("Command execution failed exit code: ").append(exitCode);
            }
        } catch (Exception e) {
            return "Error executing command: " + e.getMessage();
        }
        return outStringBuilder.toString();
    }
}
